﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using ToolUtil;
using zyconfig;
using zymarc;

namespace zyui
{
    public partial class MarcGrid : UserControl
    {
        private string _key;
        private string _kjm;
        private string _MarcText;
        private string _Nmarc; //当marc更新
        private int _MarcType;
        private bool _New;
        private string _uid;
        public MarcGrid()
        {
            InitializeComponent();
        }
        public int[] GetSubStrCountInStr(String str, String substr, int StartPos)
        {
            int foundPos = -1;
            int count = 0;
            List<int> foundItems = new List<int>();
            do
            {
                foundPos = str.IndexOf(substr, StartPos);
                if (foundPos > -1)
                {
                    StartPos = foundPos + 1;
                    count++;
                    foundItems.Add(foundPos);
                }
            } while (foundPos > -1 && StartPos < str.Length);

            return ((int[])foundItems.ToArray());
        }
        private int GetStrLength(string strdata)
        {
            int num = 0;
            char[] chArray = strdata.ToCharArray();
            for (int i = 0; i <= (chArray.Length - 1); i++)
            {
                num += this.GetCharLength(chArray[i]);
            }
            return num;
        }
        private int GetCharLength(char ch)
        {
            int num = 0;
            if ((((short)ch) < 0) || (((short)ch) > 0x80))
            {
                return (num + 2);
            }
            num++;
            return num;
        }
        private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex < 0)
                return;
            else
            {
                try
                {
                    if (e.ColumnIndex == 3)
                    {
                        string cellWord = e.Value.ToString();//单元格原本内容
                        Rectangle cellRect = e.CellBounds;//默认单元格
                        e.PaintBackground(e.ClipBounds, false);
                        //绘制背景色(被选中状态下)
                        if (e.State == (DataGridViewElementStates.Displayed | DataGridViewElementStates.Selected | DataGridViewElementStates.Visible))
                            e.PaintBackground(e.ClipBounds, true);

                        using (Brush foreColor = new SolidBrush(Color.Black), fontColor = new SolidBrush(Color.Red))
                        {
                            //分别绘制原文本和现在改变颜色的文本
                            e.Graphics.DrawString(cellWord, this.Font, foreColor, cellRect, StringFormat.GenericDefault);
                        }
                        if (cellWord.Contains('|'.ToString()))
                        {
                            string[] nrs = cellWord.Split('|');
                            for (int i = 1; i < nrs.Length; i++)
                            {
                                string str = nrs[i];
                                //Rectangle keyRect = e.CellBounds;//默认单元格
                                if (str.Length > 0)
                                {
                                    string zzd = '|'.ToString() + str.Substring(0, 1);
                                    cellWord = cellWord.Replace(zzd, "<style='color:red'>" + zzd + "</style>");
                                }
                            }
                            dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = cellWord;
                        }

                    }
                }
                catch { }
            }
        }

        public void GetGridView()
        {
            this.dataGridView1.Update();
            this.dataGridView1.Refresh();
            string str = string.Empty;
            string[] strArray = MarcText.Split(new char[] { '\x001e' });
            for (int item = 0; item < dataGridView1.Rows.Count; item++)
            {
                string name = "";
                if (dataGridView1.Rows[item].Cells[1].Value != null)
                    name = dataGridView1.Rows[item].Cells[1].Value.ToString();
                string qyt = "";
                if (dataGridView1.Rows[item].Cells[2].Value != null)
                    qyt = dataGridView1.Rows[item].Cells[2].Value.ToString();
                string nr = "";
                if (dataGridView1.Rows[item].Cells[3].Value != null)
                    nr = dataGridView1.Rows[item].Cells[3].Value.ToString();
                string oldValue = '\x001f'.ToString();
                string newValue = '@'.ToString();
                nr = nr.Replace('|', '@').Replace(newValue, oldValue);
                str += '\x001e' + name + qyt + nr;
            }
            this._Nmarc = strArray[0].ToString() + str + '\x001e';

        }
        public void SetGridView()
        {
            int num;
            DataTable table = new DataTable("marc");
            DataColumn column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "字段名称";
            column.AutoIncrement = false;
            column.Caption = "字段名称";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);
            column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "字段";
            column.AutoIncrement = false;
            column.Caption = "字段";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);
            column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "指";
            column.AutoIncrement = false;
            column.Caption = "指";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);
            column = new DataColumn();
            column.DataType = System.Type.GetType("System.String");
            column.ColumnName = "字段内容";
            column.AutoIncrement = false;
            column.Caption = "字段内容";
            column.ReadOnly = false;
            column.Unique = false;
            table.Columns.Add(column);
            string str = this._MarcText;
            string oldValue = '\x001f'.ToString();
            string newValue = '@'.ToString();
            string[] strArray = str.Replace(oldValue, newValue).Replace('@', '|').Split(new char[] { '\x001e' });
            //string[] strArray = str.Replace(oldValue, newValue).Split(new char[] { '\x001e' });
            for (num = 1; num < strArray.Length; num++)
            {
                string str4 = strArray[num].ToString();
                if (str4.Length >= 3)
                {
                    DataRow row;
                    string strNode = str4.Substring(0, 3);
                    string strT = "";
                    using (DbOperHandler _open = new Common().Doh())
                    {
                        _open.Reset();
                        _open.ConditionExpress = " MARC类型=" + this._MarcType + " and 标识符='" + strNode + "'";
                        strT = (string)_open.GetField("MARC数据字典", "名称缩写");
                    }
                    if (((strNode == "001") || (strNode == "005")) || (strNode == "008"))
                    {
                        row = table.NewRow();
                        row["字段名称"] = strT;
                        row["字段"] = strNode;
                        row["指"] = "";
                        row["字段内容"] = str4.Substring(3, str4.Length - 3);
                        table.Rows.Add(row);
                    }
                    else
                    {
                        row = table.NewRow();
                        row["字段名称"] = strT;
                        row["字段"] = strNode;
                        row["指"] = str4.Substring(3, 2);
                        row["字段内容"] = str4.Substring(5, str4.Length - 5);
                        table.Rows.Add(row);
                    }
                }
            }
            this.dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders;
            this.dataGridView1.Rows.Clear();
            for (num = 0; num <= (table.Rows.Count - 1); num++)
            {
                int num2 = this.dataGridView1.Rows.Add();
                DataGridViewRow row2 = this.dataGridView1.Rows[num2];
                row2.Cells["字段名称"].Value = table.Rows[num]["字段名称"].ToString();
                row2.Cells["字段标识"].Value = table.Rows[num]["字段"].ToString();
                row2.Cells["指示符"].Value = table.Rows[num]["指"].ToString();
                //StringBuilder html = new StringBuilder();
                string nr = table.Rows[num]["字段内容"].ToString();
                //nr = nr.Replace("|", "<font color='red'>|</font>");
                //html.Append(nr);
                row2.Cells["内容"].Value = nr;
            }
            if (!string.IsNullOrEmpty(key))
                this.saveMenuItem.Enabled = true;
            else
                this.saveMenuItem.Enabled = false;
        }

        private void munDeleteFilds_Click(object sender, EventArgs e)
        {
            int index = 0;
            if (this.dataGridView1.CurrentRow != null)
            {
                index = this.dataGridView1.CurrentRow.Index;
                if (MessageBox.Show("确认要删除【" + this.dataGridView1.CurrentRow.Cells["字段标识"].Value.ToString() + "】吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                {
                    this.dataGridView1.Rows.Remove(this.dataGridView1.CurrentRow);
                    GetGridView();
                }
            }
        }

        private void munInsertFilds_Click(object sender, EventArgs e)
        {
            int index = 0;
            if (this.dataGridView1.CurrentRow != null)
            {
                index = this.dataGridView1.CurrentRow.Index;
            }
            else
            {
                index = this.dataGridView1.Rows.Count;
            }
            this.dataGridView1.Rows.Insert(index + 1, 1);
            DataGridViewRow row = this.dataGridView1.Rows[index + 1];
            row.Cells["字段名称"].Value = "";
            row.Cells["字段标识"].Value = "";
            row.Cells["指示符"].Value = "  ";
            row.Cells["内容"].Value = "";
            this.dataGridView1.ClearSelection();
            this.dataGridView1.Rows[index + 1].Cells[1].Selected = true;
            this.dataGridView1.CurrentCell = this.dataGridView1.Rows[index + 1].Cells[1];
        }

        private void munPaste_Click(object sender, EventArgs e)
        {
            //SendKeys.Send(Keys.Control.ToString() + "{V}");
            string marc = Clipboard.GetText();
            string[] strArray = marc.Split('\n');
            string iso = string.Empty;
            for (int num = 0; num < strArray.Length; num++)
            {
                string str4 = strArray[num].ToString();
                if (str4.Length >= 3)
                {
                    string[] array = str4.Split('|');
                    string str = array[0].ToString();
                    if (str.Length >= 3)
                    {
                        string oldValue = '\x001f'.ToString();
                        string newValue = '@'.ToString();
                        string zd = str.Substring(0, 3);
                        bool flag = false;
                        using (DbOperHandler _open = new Common().Doh())
                        {
                            _open.Reset();
                            _open.ConditionExpress = " (MARC类型=1 or MARC类型=0) and 标识符='" + zd + "'";
                            flag = _open.Exist("mdict");
                        }
                        if (flag)
                        {
                            string zsf = str.Substring(3).Replace("	", "");
                            if (string.IsNullOrEmpty(zsf))
                                zsf = "  ";
                            if (zsf.Length == 1)
                                zsf += " ";
                            string nr = string.Empty;
                            for (int i = 1; i < array.Length; i++)
                            {
                                nr += oldValue + array[i].ToString().Substring(0, 1) + array[i].ToString().Substring(1).Trim();
                            }
                            //string nr1 = str4.Substring(str.Length).Replace(" ", "").Replace( '|', '@').Replace(newValue, oldValue).Replace('\n'.ToString(),"");
                            iso += '\x001e'.ToString() + zd + zsf + nr;
                        }
                    }
                }
            }
            if (!string.IsNullOrEmpty(iso))
            {
                Random ran = new Random();
                int RandKey = ran.Next(1, 999999);
                this._MarcText = "nam0" + '\x001e'.ToString() + "001" + "1".PadLeft(2, '0') + DateTime.Now.ToString("yyyy") + RandKey.ToString().PadLeft(6, '0') + '\x001e'.ToString() + "005" + DateTime.Now.ToString("yyyyMMddHHmmss.ff") + iso + '\x001e'.ToString() + "801 0" + '\x001f'.ToString() + "aCN" + '\x001f'.ToString() + "bBWZ" + '\x001f'.ToString() + "c" + DateTime.Now.ToString("yyyyMMdd") + '\x001e'.ToString();
                SetGridView();
            }
        }

        private void munRemoryEmptyFilds_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确认要清空所有空字段吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                for (int i = 0; i <= (this.dataGridView1.Rows.Count - 1); i++)
                {
                    if (this.dataGridView1.Rows[i].Cells["内容"].Value.ToString().Length <= 2)
                    {
                        this.dataGridView1.Rows.Remove(this.dataGridView1.Rows[i]);
                    }
                }
                GetGridView();
            }
        }
        private void cmMenu_Click(object sender, EventArgs e)
        {
            GetGridView();
            if (MarcText.EndsWith('\x001e'.ToString()) && !Nmarc.EndsWith('\x001e'.ToString()))
                Nmarc += '\x001e'.ToString();
            if (MarcText.EndsWith('\x001d'.ToString()) && !Nmarc.EndsWith('\x001d'.ToString()))
                Nmarc += '\x001d'.ToString();
            if (string.IsNullOrEmpty(Nmarc))
                MessageBox.Show("当前MARC记录为空");
            else
            {
                try
                {
                    Clipboard.SetText(Nmarc);
                }
                catch (Exception ex)
                {
                    Application.DoEvents();
                    Clipboard.SetText(Nmarc);
                }
            }
        }
        private void pmMenu_Click(object sender, EventArgs e)
        {
            if (Clipboard.ContainsText())
            {
                this._MarcText = Clipboard.GetText();
                MarcConvert n = new MarcConvert();
                n.MarcText = this._MarcText;
                try
                {
                    n.SetISOStr();
                    this.SetGridView();
                }
                catch
                {
                    MessageBox.Show("剪切板内容并非合法MARC格式!");
                }
            }
            else
                MessageBox.Show("剪切板没有文本!");
        }
        private void dataGridView_Leave(object sender, EventArgs e)
        {
            GetGridView();
            if (MarcText.EndsWith('\x001e'.ToString()) && !Nmarc.EndsWith('\x001e'.ToString()))
                Nmarc += '\x001e'.ToString();
            if (MarcText.EndsWith('\x001d'.ToString()) && !Nmarc.EndsWith('\x001d'.ToString()))
                Nmarc += '\x001d'.ToString();
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(Nmarc) && !Nmarc.Equals(MarcText))
            {
                if (MessageBox.Show("MARC数据已修改，是否保存？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                {
                    this.saveMarc();
                }
            }
        }
        /// <summary>
        /// 新建MARC后保存馆藏
        /// </summary>
        public void saveNmarc()
        {
            GetGridView();
            if (MarcText.EndsWith('\x001e'.ToString()) && !Nmarc.EndsWith('\x001e'.ToString()))
                Nmarc += '\x001e'.ToString();
            if (MarcText.EndsWith('\x001d'.ToString()) && !Nmarc.EndsWith('\x001d'.ToString()))
                Nmarc += '\x001d'.ToString();
            if (!string.IsNullOrEmpty(Nmarc))
            {
                bool flag = false;
                string strE = "";
                bool fc = SaveMarc.check(Nmarc, out strE);
                if (!fc)
                {
                    ShowMessageBox.ShowMessageBoxTimeout(strE, "警告", MessageBoxButtons.OK, 3000);
                    return;
                }
                MarcConvert convert = new MarcConvert();
                convert.MarcText = Nmarc;
                using (DbOperHandler _open = new Common().Doh())
                {
                    if (_open.dbType.ToString().Equals("ORACLE") || _open.odbType.ToString().Equals("ORACLE"))
                        flag = true;
                    _open.Reset();
                    _open.SqlCmd = "select 库键码 ,所属表 from 检索途径定义 where 库键码=" + kjm + " group by 所属表,库键码 order by 所属表";
                    DataTable dt = _open.GetDataTable();
                    string tName = string.Empty;
                    foreach (DataRow dRow in dt.Rows)
                    {
                        tName = dRow["所属表"].ToString().Trim();
                        Bjstj book = new Bjstj();
                        List<string> flist = new List<string>();
                        List<string> nlist = new List<string>();
                        List<int> lxlist = new List<int>();
                        book.Tname = tName;
                        _open.Reset();
                        _open.SqlCmd = "select * from 检索途径生成方式 where 库键码=" + kjm + " and 所属表='" + tName + "' order by 类型,MARC字段标识";
                        DataTable dtt = _open.GetDataTable();
                        foreach (DataRow dsRow in dtt.Rows)
                        {
                            string fildName = dsRow["表字段名"].ToString().Trim();
                            string zd = dsRow["MARC字段标识"].ToString().Trim();
                            string zzd = dsRow["子字段标识"].ToString().Trim();
                            string tzd = dsRow["同取子字段"].ToString().Trim();
                            string qzd = dsRow["其余字段"].ToString().Trim();
                            string lx = dsRow["类型"].ToString().Trim();
                            int zdcd = Convert.ToInt32(dsRow["字段长度"].ToString().Trim());
                            string nr = convert.GetASubField(zd, zzd, 1);
                            if (!string.IsNullOrEmpty(tzd))
                            {
                                //Regex zzdExp = new Regex(@"[a-zA-Z0-9]");
                                Regex regExp = new Regex(@"[^a-zA-Z0-9]");
                                if (!regExp.IsMatch(tzd.Substring(0, 1)))
                                {
                                    tzd = "," + tzd;
                                }
                                char[] chArray = tzd.ToCharArray();
                                for (int i = 0; i < chArray.Length; i++)
                                {
                                    if (i % 2 == 0)
                                    {
                                        int m = i + 1;
                                        if (m < chArray.Length)
                                        {
                                            string znr = convert.GetASubField(zd, chArray[m].ToString(), 1);
                                            if (!string.IsNullOrEmpty(znr))
                                                nr += chArray[i].ToString() + znr;
                                        }
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(qzd))
                            {
                                Regex regExp = new Regex(@"[^a-zA-Z0-9]");
                                if (!regExp.IsMatch(qzd.Substring(0, 1)))
                                {
                                    qzd = "," + qzd;
                                }
                                char[] chArray = qzd.ToCharArray();
                                for (int i = 0; i < chArray.Length; i++)
                                {
                                    if (i % 5 != 0 && i % 2 == 0)
                                    {
                                        int m = i + 1;
                                        if (m < chArray.Length)
                                        {
                                            string znr = convert.GetASubField(zd, chArray[m].ToString(), 1);
                                            if (!string.IsNullOrEmpty(znr))
                                                nr += chArray[i].ToString() + znr;
                                        }
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(nr))
                            {
                                if (fildName.Equals("题名缩写"))
                                {
                                    string[] nrs = nr.Split(new char[] { ' ' });
                                    nr = "";
                                    foreach (string str in nrs)
                                    {
                                        nr += str.Substring(0, 1).ToLower();
                                    }
                                }
                                int cd = StringUtil.GetStrLength(nr);
                                if (cd > zdcd)
                                {
                                    nr = StringUtil.SubStrByByte(nr, 0, zdcd - 3);
                                }
                                flist.Add(fildName);
                                lxlist.Add(Convert.ToInt32(lx));
                                nlist.Add(nr);
                            }
                        }
                        book.FList = flist;
                        book.LxList = lxlist;
                        book.NrList = nlist;
                        if (book.NrList.Count > 0)
                        {
                            if (tName.Equals("馆藏书目库"))
                            {
                                List<int> jmList = new List<int>();
                                _open.Reset();
                                _open.SqlCmd = " select 主键码 from 馆藏书目库 where 主键码>0 order by 主键码";
                                DataTable dr = _open.GetDataTable(); 
                                if (dr.Rows.Count > 0)
                                {
                                    for (int i = 0; i < dr.Rows.Count; i++)
                                    {
                                        jmList.Add(Convert.ToInt32(dr.Rows[i]["主键码"].ToString()));
                                    }
                                }
                                this.key = StringUtil.GetNextNumber(jmList).ToString();
                                _open.Reset();
                                for (int i = 0; i < book.NrList.Count; i++)
                                {
                                    _open.AddFieldItem(book.FList[i].ToString(), book.NrList[i]);
                                }
                                List<string> bflist = new List<string> { "标准编码", "索书号" };
                                if (!book.FList.Exists(t => t == "标准编码"))
                                {
                                    string isbn = convert.GetASubField("010", "a", 1);
                                    if (string.IsNullOrEmpty(isbn))
                                        isbn = convert.GetASubField("011", "a", 1);
                                    _open.AddFieldItem("标准编码", isbn);
                                }
                                if (!flag)
                                    _open.AddFieldItem("marc", Nmarc);
                                _open.AddFieldItem("库键码", kjm);
                                _open.AddFieldItem("主键码", this.key);
                                _open.AddFieldItem("处理日期", DateTime.Now);
                                _open.AddFieldItem("操作员", this._uid);
                                _open.AddFieldItem("修改人员", this._uid);
                                _open.Insert(tName);

                                if (flag)
                                {
                                    try
                                    {
                                        convert.SetISOStr();
                                        _open.Reset();
                                        _open.ConditionExpress = " 主键码=" + key;
                                        if (_open.Exist("MARC_DATA"))
                                        {
                                            _open.AddFieldItem("marc1", convert.ISOData);
                                            _open.Update("MARC_DATA");
                                        }
                                        else
                                        {
                                            _open.Reset();
                                            _open.AddFieldItem("marc1", convert.ISOData);
                                            _open.AddFieldItem("主键码", this.key);
                                            _open.Insert("MARC_DATA");
                                        }
                                    }
                                    catch { }
                                }
                            }
                            if (tName.Equals("检索编码库") && !string.IsNullOrEmpty(this.key))
                            {
                                _open.Reset();
                                _open.ConditionExpress = " 主键码=" + key;
                                int bm = _open.Count("检索编码库");
                                int i = 0;
                                while (i < book.NrList.Count)
                                {
                                    string isbn = book.NrList[i].Trim();
                                    if (!string.IsNullOrEmpty(isbn))
                                    {
                                        string sisbn = SqlText.BuingISBNSept(SqlText.BarCodeToISBN(isbn.Replace("-", "")));
                                        _open.AddFieldItem(book.FList[i].ToString(), sisbn);
                                        _open.AddFieldItem("类型", book.LxList[i]);
                                    }
                                    i++;
                                }
                                if (i > 0)
                                {
                                    if (bm > 0)
                                        _open.Update("检索编码库");
                                    else
                                    {
                                        _open.AddFieldItem("主键码", key);
                                        _open.Insert("检索编码库");
                                    }
                                }

                            }
                        }
                    }
                }
            }
        }
        public void savemarc()
        {
            GetGridView();
            if (MarcText.EndsWith('\x001e'.ToString()) && !Nmarc.EndsWith('\x001e'.ToString()))
                Nmarc += '\x001e'.ToString();
            if (MarcText.EndsWith('\x001d'.ToString()) && !Nmarc.EndsWith('\x001d'.ToString()))
                Nmarc += '\x001d'.ToString();
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(Nmarc))
            {
                bool flag = false;
                string strE = "";
                bool fc = SaveMarc.check(Nmarc, out strE);
                if (!fc)
                    ShowMessageBox.ShowMessageBoxTimeout(strE, "警告", MessageBoxButtons.OK, 3000);
                MarcConvert convert = new MarcConvert();
                convert.MarcText = Nmarc;
                using (DbOperHandler _open = new Common().Doh())
                {
                    if (_open.dbType.ToString().Equals("ORACLE") || _open.odbType.ToString().Equals("ORACLE"))
                        flag = true;
                    _open.Reset();
                    _open.SqlCmd = "select 库键码 ,所属表 from 检索途径定义 where 库键码=" + kjm + " group by 所属表,库键码 order by 所属表";
                    DataTable dt = _open.GetDataTable();
                    string tName = string.Empty;
                    foreach (DataRow dRow in dt.Rows)
                    {
                        tName = dRow["所属表"].ToString().Trim();
                        Bjstj book = new Bjstj();
                        List<string> flist = new List<string>();
                        List<string> nlist = new List<string>();
                        List<int> lxlist = new List<int>();
                        book.Tname = tName;
                        _open.Reset();
                        _open.SqlCmd = "select * from 检索途径生成方式 where 库键码=" + kjm + " and 所属表='" + tName + "' order by 类型,MARC字段标识";
                        DataTable dtt = _open.GetDataTable();
                        foreach (DataRow dsRow in dtt.Rows)
                        {
                            string fildName = dsRow["表字段名"].ToString().Trim();
                            string zd = dsRow["MARC字段标识"].ToString().Trim();
                            string zzd = dsRow["子字段标识"].ToString().Trim();
                            string tzd = dsRow["同取子字段"].ToString().Trim();
                            string qzd = dsRow["其余字段"].ToString().Trim();
                            string lx = dsRow["类型"].ToString().Trim();
                            int zdcd= Convert.ToInt32(dsRow["字段长度"].ToString().Trim());
                            string nr = convert.GetASubField(zd, zzd, 1);
                            if (!string.IsNullOrEmpty(tzd))
                            {
                                //Regex zzdExp = new Regex(@"[a-zA-Z0-9]");
                                Regex regExp = new Regex(@"[^a-zA-Z0-9]");
                                if (!regExp.IsMatch(tzd.Substring(0, 1)))
                                {
                                    tzd = "," + tzd;
                                }
                                char[] chArray = tzd.ToCharArray();
                                for (int i = 0; i < chArray.Length; i++)
                                {
                                    if (i % 2 == 0)
                                    {
                                        int m = i + 1;
                                        if (m < chArray.Length)
                                        {
                                            string znr = convert.GetASubField(zd, chArray[m].ToString(), 1);
                                            if (!string.IsNullOrEmpty(znr))
                                                nr += chArray[i].ToString() + znr;
                                            //Console.WriteLine(zd+":"+chArray[m].ToString() + ":" + nr);
                                        }
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(qzd))
                            {
                                Regex regExp = new Regex(@"[^a-zA-Z0-9]");
                                if (!regExp.IsMatch(qzd.Substring(0, 1)))
                                {
                                    qzd = "," + qzd;
                                }
                                char[] chArray = qzd.ToCharArray();
                                for (int i = 0; i < chArray.Length; i++)
                                {
                                    if (i % 5 != 0 && i % 2 == 0)
                                    {
                                        int m = i + 1;
                                        if (m < chArray.Length)
                                        {
                                            string znr = convert.GetASubField(zd, chArray[m].ToString(), 1);
                                            if (!string.IsNullOrEmpty(znr))
                                                nr += chArray[i].ToString() + znr;
                                        }
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(nr))
                            {
                                if (fildName.Equals("题名缩写"))
                                {
                                    string[] nrs = nr.Split(new char[] { ' ' });
                                    nr = "";
                                    foreach (string str in nrs)
                                    {
                                        nr += str.Substring(0, 1).ToLower();
                                    }
                                }
                                int cd = StringUtil.GetStrLength(nr);
                                //Console.WriteLine(nr + ":" + cd);
                                if (cd > zdcd)
                                {
                                    nr = StringUtil.SubStrByByte(nr, 0, zdcd - 3);
                                }
                                //Console.WriteLine(nr + ":cd:" + cd);
                                flist.Add(fildName);
                                lxlist.Add(Convert.ToInt32(lx));
                                nlist.Add(nr);
                            }
                        }
                        book.FList = flist;
                        book.LxList = lxlist;
                        book.NrList = nlist;
                        if (book.NrList.Count > 0)
                        {
                            if (tName.IndexOf("检索") < 0)
                            {
                                _open.Reset();
                                _open.ConditionExpress = " 主键码=" + key;
                                for (int i = 0; i < book.NrList.Count; i++)
                                {
                                    _open.AddFieldItem(book.FList[i].ToString(), book.NrList[i]);
                                }
                                List<string> bflist = new List<string> { "标准编码", "索书号" };
                                if (!book.FList.Exists(t => t == "标准编码"))
                                {
                                    string isbn = convert.GetASubField("010", "a", 1);
                                    if (string.IsNullOrEmpty(isbn))
                                        isbn = convert.GetASubField("011", "a", 1);
                                    _open.AddFieldItem("标准编码", isbn);
                                }
                                if (!flag)
                                    _open.AddFieldItem("marc", Nmarc);
                                _open.Update(tName);
                                if (flag)
                                {
                                    try
                                    {
                                        convert.SetISOStr();
                                        _open.Reset();
                                        _open.ConditionExpress = " 主键码=" + key;
                                        _open.AddFieldItem("marc1", convert.ISOData);
                                        _open.Update("MARC_DATA");
                                    }
                                    catch { }
                                }
                            }
                            else
                            {
                                if (tName.Equals("检索索书号库"))
                                {
                                    _open.Reset();
                                    _open.ConditionExpress = " 主键码=" + key;
                                    int bm = _open.Count("检索索书号库");
                                    int i = 0;
                                    while (i < book.NrList.Count)
                                    {
                                        string sh = book.NrList[i].Trim();
                                        if (bm > 0)
                                        {
                                            string ssh = _open.GetField("检索索书号库", "索书号").ToString().Trim();
                                            if (!ssh.Equals(sh))
                                            {
                                                _open.AddFieldItem(book.FList[i].ToString(), sh);
                                                _open.Update("检索索书号库");
                                            }
                                        }
                                        else
                                        {
                                            _open.AddFieldItem(book.FList[i].ToString(), sh);
                                            _open.AddFieldItem("主键码", key);
                                            _open.AddFieldItem("馆键码", 1);
                                            _open.Insert("检索索书号库");
                                        }
                                        i++;
                                    }
                                }
                                if (tName.Equals("检索编码库"))
                                {
                                    _open.Reset();
                                    _open.ConditionExpress = " 主键码=" + key;
                                    int bm = _open.Count("检索编码库");
                                    int i = 0;
                                    while (i < book.NrList.Count)
                                    {
                                        string isbn = book.NrList[i].Trim();
                                        if (!string.IsNullOrEmpty(isbn))
                                        {
                                            string sisbn = SqlText.BuingISBNSept(SqlText.BarCodeToISBN(isbn.Replace("-", "")));
                                            _open.AddFieldItem(book.FList[i].ToString(), sisbn);
                                            _open.AddFieldItem("类型", book.LxList[i]);
                                        }
                                        i++;
                                    }
                                    if (i > 0)
                                    {
                                        if (bm > 0)
                                            _open.Update("检索编码库");
                                        else
                                        {
                                            _open.AddFieldItem("主键码", key);
                                            _open.Insert("检索编码库");
                                        }
                                    }

                                }
                                if (tName.Equals("检索一对多库"))
                                {
                                    _open.Reset();
                                    _open.ConditionExpress = "主键码=" + key;
                                    _open.Delete("检索一对多库");
                                    for (int i = 0; i < book.NrList.Count; i++)
                                    {
                                        _open.Reset();
                                        _open.AddFieldItem("主键码", key);
                                        _open.AddFieldItem(book.FList[i].ToString(), book.NrList[i].Trim());
                                        _open.AddFieldItem("类型", book.LxList[i]);
                                        _open.Insert("检索一对多库");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        private void saveMenuItem_Click(object sender, EventArgs e)
        {
            GetGridView();
            if (MarcText.EndsWith('\x001e'.ToString()) && !Nmarc.EndsWith('\x001e'.ToString()))
                Nmarc += '\x001e'.ToString();
            if (MarcText.EndsWith('\x001d'.ToString()) && !Nmarc.EndsWith('\x001d'.ToString()))
                Nmarc += '\x001d'.ToString();
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(Nmarc))
                this.saveMarc();
        }
        public void saveMarc()
        {
            bool flag = false;
            GetGridView();
            string strE = "";
            bool fc = SaveMarc.check(Nmarc, out strE);
            if (!fc)
                ShowMessageBox.ShowMessageBoxTimeout(strE, "警告", MessageBoxButtons.OK, 3000);
            if (MessageBox.Show(strE + ",MARC数据已修改，是否更新检索项？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                MarcConvert convert = new MarcConvert();
                convert.MarcText = Nmarc;
                using (DbOperHandler _open = new Common().Doh())
                {
                    if (_open.dbType.ToString().Equals("ORACLE") || _open.odbType.ToString().Equals("ORACLE"))
                        flag = true;
                    _open.Reset();
                    _open.SqlCmd = "select 库键码 ,所属表 from 检索途径定义 where 库键码=" + kjm + " group by 所属表,库键码 order by 所属表";
                    DataTable dt = _open.GetDataTable();
                    string tName = string.Empty;
                    foreach (DataRow dRow in dt.Rows)
                    {
                        tName = dRow["所属表"].ToString().Trim();
                        Bjstj book = new Bjstj();
                        List<string> flist = new List<string>();
                        List<string> nlist = new List<string>();
                        List<int> lxlist = new List<int>();
                        book.Tname = tName;
                        _open.Reset();
                        _open.SqlCmd = "select * from 检索途径生成方式 where 库键码=" + kjm + " and 所属表='" + tName + "' order by 类型,MARC字段标识";
                        DataTable dtt = _open.GetDataTable();
                        foreach (DataRow dsRow in dtt.Rows)
                        {
                            string fildName = dsRow["表字段名"].ToString().Trim();
                            string zd = dsRow["MARC字段标识"].ToString().Trim();
                            string zzd = dsRow["子字段标识"].ToString().Trim();
                            string tzd = dsRow["同取子字段"].ToString().Trim();
                            string qzd = dsRow["其余字段"].ToString().Trim();
                            int zdcd = Convert.ToInt32(dsRow["字段长度"].ToString().Trim()); 
                            string lx = dsRow["类型"].ToString().Trim();
                            string nr = convert.GetASubField(zd, zzd, 1);
                            //Console.WriteLine(zd + ":" + zzd + ":" + nr);
                            if (!string.IsNullOrEmpty(tzd))
                            {
                                //Regex zzdExp = new Regex(@"[a-zA-Z0-9]");
                                Regex regExp = new Regex(@"[^a-zA-Z0-9]");
                                if (!regExp.IsMatch(tzd.Substring(0, 1)))
                                {
                                    tzd = "," + tzd;
                                }
                                char[] chArray = tzd.ToCharArray();
                                for (int i = 0; i < chArray.Length; i++)
                                {
                                    if (i % 2 == 0)
                                    {
                                        int m = i + 1;
                                        if (m < chArray.Length)
                                        {
                                            string znr = convert.GetASubField(zd, chArray[m].ToString(), 1);
                                            if (!string.IsNullOrEmpty(znr))
                                                nr += chArray[i].ToString() + znr;
                                            //Console.WriteLine(zd+":"+chArray[m].ToString() + ":" + nr);
                                        }
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(qzd))
                            {
                                Regex regExp = new Regex(@"[^a-zA-Z0-9]");
                                if (!regExp.IsMatch(qzd.Substring(0, 1)))
                                {
                                    qzd = "," + qzd;
                                }
                                char[] chArray = qzd.ToCharArray();
                                for (int i = 0; i < chArray.Length; i++)
                                {
                                    if (i % 5 != 0 && i % 2 == 0)
                                    {
                                        int m = i + 1;
                                        if (m < chArray.Length)
                                        {
                                            string znr = convert.GetASubField(zd, chArray[m].ToString(), 1);
                                            if (!string.IsNullOrEmpty(znr))
                                                nr += chArray[i].ToString() + znr;
                                        }
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(nr))
                            {
                                //Console.WriteLine(nr);
                                if (fildName.Equals("题名缩写"))
                                {
                                    string[] nrs = nr.Split(new char[] { ' ' });
                                    nr = "";
                                    foreach (string str in nrs)
                                    {
                                        nr += str.Substring(0, 1).ToLower();
                                    }
                                }
                                int cd = StringUtil.GetStrLength(nr);
                                //Console.WriteLine(nr + ":" + cd);
                                if (cd > zdcd)
                                {
                                    nr = StringUtil.SubStrByByte(nr, 0, zdcd - 3);
                                }
                                flist.Add(fildName);
                                lxlist.Add(Convert.ToInt32(lx));
                                nlist.Add(nr);
                            }
                        }
                        book.FList = flist;
                        book.LxList = lxlist;
                        book.NrList = nlist;
                        if (book.NrList.Count > 0)
                        {
                            if (tName.IndexOf("检索") < 0)
                            {
                                _open.Reset();
                                _open.ConditionExpress = " 主键码=" + key;
                                for (int i = 0; i < book.NrList.Count; i++)
                                {
                                    _open.AddFieldItem(book.FList[i].ToString(), book.NrList[i]);
                                }
                                List<string> bflist = new List<string> { "标准编码", "索书号" };
                                if (!book.FList.Exists(t => t == "标准编码"))
                                {
                                    string isbn = convert.GetASubField("010", "a", 1);
                                    if (string.IsNullOrEmpty(isbn))
                                        isbn = convert.GetASubField("011", "a", 1);
                                    _open.AddFieldItem("标准编码", isbn);
                                }
                                if (!flag)
                                    _open.AddFieldItem("marc", Nmarc);
                                _open.Update(tName);
                                if (flag)
                                {
                                    try
                                    {
                                        convert.SetISOStr();
                                        _open.Reset();
                                        _open.ConditionExpress = " 主键码=" + key;
                                        _open.AddFieldItem("marc1", convert.ISOData);
                                        _open.Update("MARC_DATA");
                                    }
                                    catch { }
                                }
                            }
                            else
                            {
                                if (tName.Equals("检索索书号库"))
                                {
                                    _open.Reset();
                                    _open.ConditionExpress = " 主键码=" + key;
                                    int bm = _open.Count("检索索书号库");
                                    int i = 0;
                                    while (i < book.NrList.Count)
                                    {
                                        string sh = book.NrList[i].Trim();
                                        if (bm > 0)
                                        {
                                            string ssh = _open.GetField("检索索书号库", "索书号").ToString().Trim();
                                            if (!ssh.Equals(sh))
                                            {
                                                _open.AddFieldItem(book.FList[i].ToString(), sh);
                                                _open.Update("检索索书号库");
                                            }
                                        }
                                        else
                                        {
                                            _open.AddFieldItem(book.FList[i].ToString(), sh);
                                            _open.AddFieldItem("主键码", key);
                                            _open.AddFieldItem("馆键码", 1);
                                            _open.Insert("检索索书号库");
                                        }
                                        i++;
                                    }
                                }
                                if (tName.Equals("检索编码库"))
                                {
                                    _open.Reset();
                                    _open.ConditionExpress = " 主键码=" + key;
                                    int bm = _open.Count("检索编码库");
                                    int i = 0;
                                    while (i < book.NrList.Count)
                                    {
                                        string isbn = book.NrList[i].Trim();
                                        if (!string.IsNullOrEmpty(isbn))
                                        {
                                            string sisbn = SqlText.BuingISBNSept(SqlText.BarCodeToISBN(isbn.Replace("-", "")));
                                            _open.AddFieldItem(book.FList[i].ToString(), sisbn);
                                            _open.AddFieldItem("类型", book.LxList[i]);
                                        }
                                        i++;
                                    }
                                    if (i > 0)
                                    {
                                        if (bm > 0)
                                            _open.Update("检索编码库");
                                        else
                                        {
                                            _open.AddFieldItem("主键码", key);
                                            _open.Insert("检索编码库");
                                        }
                                    }

                                }
                                if (tName.Equals("检索一对多库"))
                                {
                                    _open.Reset();
                                    _open.ConditionExpress = "主键码=" + key;
                                    _open.Delete("检索一对多库");
                                    for (int i = 0; i < book.NrList.Count; i++)
                                    {
                                        _open.Reset();
                                        _open.AddFieldItem("主键码", key);
                                        _open.AddFieldItem(book.FList[i].ToString(), book.NrList[i].Trim());
                                        _open.AddFieldItem("类型", book.LxList[i]);
                                        _open.Insert("检索一对多库");
                                    }
                                }
                                /**
                                if (tName.Equals("检索多对多库"))
                                {
                                    _open.Reset();
                                    _open.SqlCmd = "select * from 检索联接库 where 主键码=" + key;
                                    DataTable ddt = _open.GetDataTable();
                                    foreach(DataRow drow in dt.Rows)
                                    {
                                        _open.Reset();
                                        _open.ConditionExpress = "子键码=" + drow["子键码"];
                                        _open.Delete("检索多对多库");
                                    }
                                    _open.Reset();
                                    _open.SqlCmd = "select * from 检索联接库 where 主键码=" + key;
                                    _open.Delete("检索联接库");
                                    _open.Reset();
                                    int zjm = Convert.ToInt32(_open.MaxValue("检索多对多库", "子键码").ToString());
                                    for (int i = 0; i < book.NrList.Count; i++)
                                    {
                                        _open.Reset();
                                        _open.AddFieldItem("子键码", zjm+i+1);
                                        _open.AddFieldItem(book.FList[i].ToString(), book.NrList[i].Trim());
                                        _open.AddFieldItem("类型", book.LxList[i]);
                                        _open.Insert("检索多对多库");
                                        _open.Reset();
                                        _open.AddFieldItem("主键码", key);
                                        _open.AddFieldItem("子键码", zjm + i + 1);
                                        _open.Insert("检索联接库");
                                    }
                                }
                                **/
                            }
                            //Console.WriteLine(JsonConvert.SerializeObject(book));
                        }
                    }
                }
            }

        }
        public string key
        {
            get
            {
                return this._key;
            }
            set
            {
                this._key = value;
            }
        }
        public string MarcText
        {
            get
            {
                return this._MarcText;
            }
            set
            {
                this._MarcText = value;
            }
        }
        public string Nmarc
        {
            get
            {
                return this._Nmarc;
            }
            set
            {
                this._Nmarc = value;
            }
        }
        public int MarcType
        {
            get
            {
                return this._MarcType;
            }
            set
            {
                this._MarcType = value;
            }
        }
        public string kjm
        {
            get
            {
                return this._kjm;
            }
            set
            {
                this._kjm = value;
            }
        }
         public bool New
        {
            get { return this._New; }
            set { this._New = value; }
        }

        public string Uid
        {
            get { return this._uid; }
            set { this._uid = value; }
        }

        private void pyMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView1.Rows.Count > 0)
            {
                GetGridView();
                MarcConvert n = new MarcConvert();
                n.MarcText= Nmarc;
                string[] zds = new string[] { "200", "701", "702", "711", "712" };
                foreach (string szd in zds)
                {
                    int m = n.GetFieldCount(szd);
                    for (int i = 1; i <= m; i++)
                    {
                        string nt = n.GetASubField(szd, "a", i);
                        string str = string.Empty;
                        if (!string.IsNullOrEmpty(nt))
                        {
                            var rlt = StringAna.getString(nt);
                            if (rlt != null)
                            {
                                foreach (var item in rlt)
                                {
                                    str += StringAna.getPin(item);
                                }
                            }
                        }
                        if (!string.IsNullOrEmpty(str))
                        {
                            //str = "|9" + str.Substring(0, str.Length - 1);
                            str = str.Substring(0, str.Length - 1);
                            n.ReplaceSubfield(szd, "9", i, str);
                            /**
                            int index = Nmarc.IndexOf(nt);
                            StringBuilder sb = new StringBuilder(Nmarc);
                            sb.Insert(index + nt.Length, str);//插入
                            this._MarcText = sb.ToString();
                            **/
                            this._MarcText = n.MarcText;
                        }
                    }
                }
                SetGridView();
                xrsjk(n.MarcText);
            }
        }
        public void zdmenu(MarcConvert convert)
        {
            string zrz = convert.GetASubField("200", "f", 1);
            string author = convert.GetASubField("701", "a", 1).Trim();
            if (string.IsNullOrEmpty(author))
                author = convert.GetASubField("711", "a", 1).Trim();
            if (string.IsNullOrEmpty(author))
            {
                using (DbOperHandler _open = new Common().Doh())
                {
                    _open.Reset();
                    _open.ConditionExpress = "键码=1";
                    string zrdy = _open.GetField("系统参数定义", "定义").ToString();
                    string[] zrds = zrdy.Split('@');
                    Array.Reverse(zrds);
                    if (!string.IsNullOrEmpty(zrz))
                    {
                        zrz = zrz.Replace("，", ",");
                        int qs = 0;
                        foreach (string str in zrds)
                        {
                            qs = zrz.LastIndexOf(str);
                            if (qs > -1)
                                break;
                        }
                        string[] zrzs = zrz.Split(',');
                        for (int i = 0; i < zrzs.Length; i++)
                        {
                            string zr = zrzs[i];
                            if (i == zrzs.Length - 1)
                            {
                                foreach (string str in zrds)
                                {
                                    zr = zr.Replace(str, "");
                                }
                            }
                            convert.ReplaceSubfield("701", "a", i + 1, zr);
                            if (qs > -1)
                            {
                                string zrfs = zrz.Substring(qs);
                                convert.ReplaceSubfield("701", "4", i + 1, zrfs);
                            }
                        }
                    }
                    string fyz = convert.GetASubField("200", "g", 1);
                    if (!string.IsNullOrEmpty(fyz))
                    {
                        fyz = fyz.Replace("，", ",");
                        int qs = 0;
                        foreach (string str in zrds)
                        {
                            qs = fyz.LastIndexOf(str);
                            if (qs > -1)
                                break;
                        }
                        string[] zrzs = fyz.Split(',');
                        for (int i = 0; i < zrzs.Length; i++)
                        {
                            string zr = zrzs[i];
                            if (i == zrzs.Length - 1)
                            {
                                foreach (string str in zrds)
                                {
                                    zr = zr.Replace(str, "");
                                }
                            }
                            convert.ReplaceSubfield("702", "a", i + 1, zr);
                            if (qs > -1)
                            {
                                string fyfs = fyz.Substring(qs);
                                convert.ReplaceSubfield("702", "4", i + 1, fyfs);
                            }
                        }
                    }
                }
            }
            string apy = convert.GetASubField("701", "9", 1);
            if (string.IsNullOrEmpty(apy))
                apy = convert.GetASubField("711", "9", 1);
            if (!string.IsNullOrEmpty(apy))
                apy = apy.Substring(0, 1).ToUpper();

            string gce = "";
            string F905D = "";
            string ygce = convert.GetASubField("905", "e", 1).Trim();
            string ygcd = convert.GetASubField("905", "d", 1).Trim();
            string ygcv = convert.GetASubField("905", "v", 1).Trim();
            if (string.IsNullOrEmpty(ygcd))
            {
                using (DbOperHandler _open = new Common().Doh())
                {
                    _open.Reset();
                    _open.ConditionExpress = "库键码=" + this._kjm;
                    string fld = _open.GetField("书目数据库定义", "中图分类字段").ToString().Trim();
                    F905D = convert.GetASubField(fld.Substring(0, 3), fld.Substring(3), 1);
                }
            }
            else
            {
                if (MessageBox.Show("905d已存在，是否更新吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                {
                    using (DbOperHandler _open = new Common().Doh())
                    {
                        _open.Reset();
                        _open.ConditionExpress = "库键码=" + this._kjm;
                        string fld = _open.GetField("书目数据库定义", "中图分类字段").ToString().Trim();
                        F905D = convert.GetASubField(fld.Substring(0, 3), fld.Substring(3), 1);
                    }
                }
                else
                    F905D = ygcd;
            }
            if (string.IsNullOrEmpty(ygce))
            {
                using (DbOperHandler _open = new Common().Doh())
                {
                    _open.Reset();
                    _open.ConditionExpress = "库键码=" + this._kjm;
                    if (!string.IsNullOrEmpty(author))
                    {
                        string zzd = _open.GetField("书目数据库定义", "F905E内容").ToString().Trim();
                        if (zzd.Equals("四角号码"))
                        {
                            string strAuthorNumber = "", strError = "";
                            GetSjhm.GetSjhmAuthorNumber(author, out strAuthorNumber, out strError);
                            //Console.WriteLine(apy + strAuthorNumber + ":" + strError);
                            gce += strAuthorNumber;
                        }
                        if (zzd.Equals("著者号"))
                        {
                            _open.Reset();
                            _open.ConditionExpress = "authname='" + author + "'";
                            bool f = _open.Exist("authcode");
                            if (f)
                            {
                                string authcode = _open.GetField("authcode", "authcode2").ToString().Trim();
                                if (string.IsNullOrEmpty(authcode))
                                    authcode = _open.GetField("authcode", "authcode").ToString().Trim();
                                gce += authcode;
                            }
                            else
                            {
                                string au1 = author.Substring(0, 1);
                                string au2 = "";
                                if (author.Length > 1)
                                    au2 = author.Substring(1, 1);
                                string apy1 = convert.GetASubField("701", "9", 1);
                                if (string.IsNullOrEmpty(apy1))
                                    apy1 = convert.GetASubField("711", "9", 1);
                                if (string.IsNullOrEmpty(apy1))
                                    apy1 = convert.GetASubField("711", "9", 1);
                                string toppy = string.Empty;
                                if (!string.IsNullOrEmpty(apy1))
                                {
                                    if (toppy.Contains(" "))
                                    {
                                        toppy = apy1.Split(' ')[1].ToString().Substring(0, 1).ToUpper();
                                        toppy += apy1.Split(' ')[01].ToString().Substring(1);
                                    }
                                    else
                                    {
                                        toppy = apy1.Substring(0, 1).ToUpper();
                                        toppy += apy1.Substring(1);
                                    }
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(au2))
                                    {
                                        string zpy = StringAna.getPin(au2);
                                        toppy = zpy.Substring(0, 1).ToUpper();
                                        toppy += zpy.Substring(1);
                                    }
                                }
                                if (!string.IsNullOrEmpty(toppy))
                                {
                                    int pcd = toppy.Length;
                                    for (int i = pcd; i > 0; i--)
                                    {
                                        string sql = "chn_char ='" + au1 + "' and top_py<='" + toppy.Substring(0, i) + "' and btm_py>='" + toppy.Substring(0, i) + "~'";
                                        _open.Reset();
                                        _open.ConditionExpress = sql;
                                        bool cf = _open.Exist("auth_nam");
                                        if (cf)
                                        {
                                            if (string.IsNullOrEmpty(apy))
                                                apy = StringAna.getPin(au1).Substring(0, 1).ToUpper();
                                            gce += apy + _open.GetField("auth_nam", "code_num");
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                if (MessageBox.Show("905e已存在，是否更新吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                {
                    using (DbOperHandler _open = new Common().Doh())
                    {
                        _open.Reset();
                        _open.ConditionExpress = "库键码=" + this._kjm;
                        if (!string.IsNullOrEmpty(author))
                        {
                            string zzd = _open.GetField("书目数据库定义", "F905E内容").ToString().Trim();
                            if (zzd.Equals("四角号码"))
                            {
                                string strAuthorNumber = "", strError = "";
                                GetSjhm.GetSjhmAuthorNumber(author, out strAuthorNumber, out strError);
                                //Console.WriteLine(apy + strAuthorNumber + ":" + strError);
                                gce += strAuthorNumber;
                            }
                            if (zzd.Equals("著者号"))
                            {
                                _open.Reset();
                                _open.ConditionExpress = "authname='" + author + "'";
                                bool f = _open.Exist("authcode");
                                if (f)
                                {
                                    string authcode = _open.GetField("authcode", "authcode2").ToString().Trim();
                                    if (string.IsNullOrEmpty(authcode))
                                        authcode = _open.GetField("authcode", "authcode").ToString().Trim();
                                    gce += authcode;
                                }
                                else
                                {
                                    string au1 = author.Substring(0, 1);
                                    string au2 = "";
                                    if (author.Length > 1)
                                        au2 = author.Substring(1, 1);
                                    string apy1 = convert.GetASubField("701", "9", 1);
                                    if (string.IsNullOrEmpty(apy1))
                                        apy1 = convert.GetASubField("711", "9", 1);
                                    string toppy = string.Empty;
                                    if (!string.IsNullOrEmpty(apy1))
                                    {
                                        //toppy = apy1.Split(' ')[1].ToString().Substring(0, 1).ToUpper();
                                        toppy = apy1.Split(' ')[1].ToString().Substring(0, 1).ToUpper();
                                        toppy += apy1.Split(' ')[1].ToString().Substring(1);
                                    }
                                    else
                                    {
                                        if (!string.IsNullOrEmpty(au2))
                                        {
                                            string zpy = StringAna.getPin(au2);
                                            toppy = zpy.Substring(0, 1).ToUpper();
                                            toppy += zpy.Substring(1);
                                        }
                                    }
                                    if (!string.IsNullOrEmpty(toppy))
                                    {
                                        int pcd = toppy.Length;
                                        for (int i = pcd; i > 0; i--)
                                        {
                                            string sql = "chn_char ='" + au1 + "' and (top_py='" + toppy.Substring(0, i) + "' or btm_py='" + toppy.Substring(0, i) + "~')";
                                            _open.Reset();
                                            _open.ConditionExpress = sql;
                                            bool cf = _open.Exist("auth_nam");
                                            //Console.WriteLine(sql);
                                            if (cf)
                                            {
                                                if (string.IsNullOrEmpty(apy))
                                                    apy = StringAna.getPin(au1).Substring(0, 1).ToUpper();
                                                gce += apy + _open.GetField("auth_nam", "code_num");
                                                break;
                                            }
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    gce = ygce;
                }
            }
            using (DbOperHandler _open = new Common().Doh())
            {
                if (!string.IsNullOrEmpty(F905D))
                {
                    if(!string.IsNullOrEmpty(gce) && gce.Contains("."))
                    {
                        bool f1 = false,f2 = false;
                        try
                        {
                            int gcee = Convert.ToInt32(gce.Split('.')[1]);
                            for(int i = gcee; i > 0; i--)
                            {
                                string str = gce.Split('.')[0] + "." + i.ToString();
                                _open.Reset();
                                _open.ConditionExpress = "索书号like N'" + str + "%'";
                                f1 = _open.Exist("馆藏书目库");
                                _open.Reset();
                                _open.ConditionExpress = "索书号 like N'" + str + "%'";
                                f2 = _open.Exist("检索索书号库");
                                if( f1 || f2)
                                {
                                    gce = str;
                                    break;
                                }
                            }
                        }
                        catch { }
                        if (!f1 && !f2)
                            gce = gce.Split('.')[0];
                    }
                    while (true)
                    {
                        string sql = "索书号='" + (F905D + "/" + gce+"/"+ygcv) + "'";
                        if (string.IsNullOrEmpty(gce))
                            sql = sql.Replace("/" + gce, "");
                        if (string.IsNullOrEmpty(ygcv))
                            sql = sql.Replace("/" + ygcv, "");
                        _open.Reset();
                        _open.ConditionExpress = sql;
                        bool csh = _open.Exist("检索索书号库");
                        if (!csh)
                            break;
                        else
                        {
                            string szjm = _open.GetField("检索索书号库", "主键码").ToString().Trim();
                            if (this.key.Trim().Equals(szjm))
                                break;
                            else
                            {
                                string[] gces = gce.Split('.');
                                if (gces.Length == 1)
                                {
                                    gce += ".1";
                                }
                                else
                                {
                                    gce = gces[0] + "." + (Convert.ToInt32(gces[1]) + 1);
                                }
                            }
                        }
                    }
                }
            }
            if (!string.IsNullOrEmpty(F905D))
            {
                convert.ReplaceSubfield("905", "d", 1, F905D);
                if (!string.IsNullOrEmpty(gce))
                {
                    convert.ReplaceSubfield("905", "e", 1, gce);
                    using (DbOperHandler _open = new Common().Doh())
                    {
                        _open.Reset();
                        _open.ConditionExpress = "authname='" + author + "'";
                        _open.AddFieldItem("authcode2", gce);
                        _open.Update("authcode");
                    }
                }
                
            }
            else
            {
                ShowMessageBox.ShowMessageBoxTimeout("905D字段内容为空，请检查690字段", "警告", MessageBoxButtons.OK, 3000);
            }
        }
        private void zdMenuItem_Click(object sender, EventArgs e)
        {
            MarcConvert convert = new MarcConvert();
            convert.MarcText= this._MarcText;
            string zrz = convert.GetASubField("200", "f", 1);
            string author = convert.GetASubField("701", "a", 1).Trim();
            if (string.IsNullOrEmpty(author))
                author = convert.GetASubField("711", "a", 1).Trim();
            if (string.IsNullOrEmpty(author))
            {
                using (DbOperHandler _open = new Common().Doh())
                {
                    _open.Reset();
                    _open.ConditionExpress = "键码=1";
                    string zrdy = _open.GetField("系统参数定义", "定义").ToString();
                    string[] zrds = zrdy.Split('@');
                    Array.Reverse(zrds);
                    if (!string.IsNullOrEmpty(zrz))
                    {
                        zrz = zrz.Replace("，", ",");
                        int qs = 0;
                        foreach (string str in zrds)
                        {
                            qs = zrz.LastIndexOf(str);
                            if (qs > -1)
                                break;
                        }
                        //Console.WriteLine("4wz:" + (zrz.Length - qs - 1).ToString()+":"+ zrz.Length+":"+qs);

                        string[] zrzs = zrz.Split(',');
                        for (int i = 0; i < zrzs.Length; i++)
                        {
                            string zr = zrzs[i];
                            if (i == zrzs.Length - 1)
                            {
                                foreach (string str in zrds)
                                {
                                    zr = zr.Replace(str, "");
                                }
                            }
                            convert.ReplaceSubfield("701", "a", i + 1, zr);
                            if (qs > -1)
                            {
                                string zrfs = zrz.Substring(qs);
                                convert.ReplaceSubfield("701", "4", i + 1, zrfs);
                            }
                        }
                    }
                    string fyz = convert.GetASubField("200", "g", 1);
                    if (!string.IsNullOrEmpty(fyz))
                    {
                        fyz = fyz.Replace("，", ",");
                        int qs = 0;
                        foreach (string str in zrds)
                        {
                            qs = fyz.LastIndexOf(str);
                            if (qs > -1)
                                break;
                        }
                        string[] zrzs = fyz.Split(',');
                        for (int i = 0; i < zrzs.Length; i++)
                        {
                            string zr = zrzs[i];
                            if (i == zrzs.Length - 1)
                            {
                                foreach (string str in zrds)
                                {
                                    zr = zr.Replace(str, "");
                                }
                            }
                            convert.ReplaceSubfield("702", "a", i + 1, zr);
                            if (qs > -1)
                            {
                                string fyfs = fyz.Substring(qs);
                                convert.ReplaceSubfield("702", "4", i + 1, fyfs);
                            }
                        }
                    }
                }
            }
            string apy = convert.GetASubField("701", "9", 1);
            if (string.IsNullOrEmpty(apy))
                apy = convert.GetASubField("711", "9", 1);
            if (!string.IsNullOrEmpty(apy))
                apy = apy.Substring(0, 1).ToUpper();

            string gce = "";
            string F905D = "";
            string ygce = convert.GetASubField("905", "e", 1).Trim();
            string ygcd = convert.GetASubField("905", "d", 1).Trim();
            if (string.IsNullOrEmpty(ygcd))
            {
                using (DbOperHandler _open = new Common().Doh())
                {
                    _open.Reset();
                    _open.ConditionExpress = "库键码=" + this._kjm;
                    string fld = _open.GetField("书目数据库定义", "中图分类字段").ToString().Trim();
                    F905D = convert.GetASubField(fld.Substring(0, 3), fld.Substring(3), 1);
                }
            }
            else
            {
                if (MessageBox.Show("905d已存在，是否更新吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                {
                    using (DbOperHandler _open = new Common().Doh())
                    {
                        _open.Reset();
                        _open.ConditionExpress = "库键码=" + this._kjm;
                        string fld = _open.GetField("书目数据库定义", "中图分类字段").ToString().Trim();
                        F905D = convert.GetASubField(fld.Substring(0, 3), fld.Substring(3), 1);
                    }
                }
                else
                    F905D = ygcd;
            }
            if (string.IsNullOrEmpty(ygce))
            {
                using (DbOperHandler _open = new Common().Doh())
                {
                    _open.Reset();
                    _open.ConditionExpress = "库键码=" + this._kjm;
                    if (!string.IsNullOrEmpty(author))
                    {
                        string zzd = _open.GetField("书目数据库定义", "F905E内容").ToString().Trim();
                        if (zzd.Equals("四角号码"))
                        {
                            string strAuthorNumber = "", strError = "";
                            GetSjhm.GetSjhmAuthorNumber(author, out strAuthorNumber, out strError);
                            //Console.WriteLine(apy + strAuthorNumber + ":" + strError);
                            gce += strAuthorNumber;
                        }
                        if (zzd.Equals("著者号"))
                        {
                            _open.Reset();
                            _open.ConditionExpress = "authname='" + author + "'";
                            bool f = _open.Exist("authcode");
                            if (f)
                            {
                                string authcode = _open.GetField("authcode", "authcode2").ToString().Trim();
                                if (string.IsNullOrEmpty(authcode))
                                    authcode = _open.GetField("authcode", "authcode").ToString().Trim();
                                gce += authcode;
                            }
                            else
                            {
                                string au1 = author.Substring(0, 1);
                                string au2 = "";
                                if (author.Length > 1)
                                    au2 = author.Substring(1, 1);
                                string apy1 = convert.GetASubField("701", "9", 1);
                                if (string.IsNullOrEmpty(apy1))
                                    apy1 = convert.GetASubField("711", "9", 1);
                                if (string.IsNullOrEmpty(apy1))
                                    apy1 = convert.GetASubField("711", "9", 1);
                                string toppy = string.Empty;
                                if (!string.IsNullOrEmpty(apy1))
                                {
                                    //toppy = apy1.Split(' ')[1].ToString().Substring(0, 1).ToUpper();
                                    toppy = apy1.Split(' ')[1].ToString().Substring(0, 1).ToUpper();
                                    toppy += apy1.Split(' ')[1].ToString().Substring(1);
                                }
                                else
                                {
                                    if (!string.IsNullOrEmpty(au2))
                                    {
                                        string zpy = StringAna.getPin(au2);
                                        toppy = zpy.Substring(0, 1).ToUpper();
                                        toppy += zpy.Substring(1);
                                    }
                                }
                                if (!string.IsNullOrEmpty(toppy))
                                {
                                    int pcd = toppy.Length;
                                    for (int i = pcd; i > 0; i--)
                                    {
                                        string sql = "chn_char ='" + au1 + "' and top_py<='" + toppy.Substring(0, i) + "' and btm_py>='" + toppy.Substring(0, i) + "~'";
                                        _open.Reset();
                                        _open.ConditionExpress = sql;
                                        bool cf = _open.Exist("auth_nam");
                                        if (cf)
                                        {
                                            if (string.IsNullOrEmpty(apy))
                                                apy = StringAna.getPin(au1).Substring(0, 1).ToUpper();
                                            gce += apy + _open.GetField("auth_nam", "code_num");
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                if (MessageBox.Show("905e已存在，是否更新吗？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
                {
                    using (DbOperHandler _open = new Common().Doh())
                    {
                        _open.Reset();
                        _open.ConditionExpress = "库键码=" + this._kjm;
                        if (!string.IsNullOrEmpty(author))
                        {
                            string zzd = _open.GetField("书目数据库定义", "F905E内容").ToString().Trim();
                            if (zzd.Equals("四角号码"))
                            {
                                string strAuthorNumber = "", strError = "";
                                GetSjhm.GetSjhmAuthorNumber(author, out strAuthorNumber, out strError);
                                //Console.WriteLine(apy + strAuthorNumber + ":" + strError);
                                gce += strAuthorNumber;
                            }
                            if (zzd.Equals("著者号"))
                            {
                                _open.Reset();
                                _open.ConditionExpress = "authname='" + author + "'";
                                bool f = _open.Exist("authcode");
                                if (f)
                                {
                                    string authcode = _open.GetField("authcode", "authcode2").ToString().Trim();
                                    if (string.IsNullOrEmpty(authcode))
                                        authcode = _open.GetField("authcode", "authcode").ToString().Trim();
                                    gce += authcode;
                                }
                                else
                                {
                                    string au1 = author.Substring(0, 1);
                                    string au2 = "";
                                    if (author.Length > 1)
                                        au2 = author.Substring(1, 1);
                                    string apy1 = convert.GetASubField("701", "9", 1);
                                    if (string.IsNullOrEmpty(apy1))
                                        apy1 = convert.GetASubField("711", "9", 1);
                                    string toppy = string.Empty;
                                    if (!string.IsNullOrEmpty(apy1))
                                    {
                                        //toppy = apy1.Split(' ')[1].ToString().Substring(0, 1).ToUpper();
                                        toppy = apy1.Split(' ')[1].ToString().Substring(0, 1).ToUpper();
                                        toppy += apy1.Split(' ')[1].ToString().Substring(1);
                                        //Console.WriteLine(": " + toppy);
                                    }
                                    else
                                    {
                                        if (!string.IsNullOrEmpty(au2))
                                        {
                                            string zpy = StringAna.getPin(au2);
                                            toppy = zpy.Substring(0, 1).ToUpper();
                                            toppy += zpy.Substring(1);
                                        }
                                    }
                                    if (!string.IsNullOrEmpty(toppy))
                                    {
                                        int pcd = toppy.Length;
                                        for (int i = pcd; i > 0; i--)
                                        {
                                            string sql = "chn_char ='" + au1 + "' and (top_py='" + toppy.Substring(0, i) + "' or btm_py='" + toppy.Substring(0, i) + "~')";
                                            _open.Reset();
                                            _open.ConditionExpress = sql;
                                            bool cf = _open.Exist("auth_nam");
                                            //Console.WriteLine(sql);
                                            if (cf)
                                            {
                                                if (string.IsNullOrEmpty(apy))
                                                    apy = StringAna.getPin(au1).Substring(0, 1).ToUpper();
                                                gce += apy + _open.GetField("auth_nam", "code_num");
                                                break;
                                            }
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    gce = ygce;
                }
            }
            using (DbOperHandler _open = new Common().Doh())
            {
                if (!string.IsNullOrEmpty(F905D))
                {
                    if (!string.IsNullOrEmpty(gce) && gce.Contains("."))
                    {
                        bool f1 = false, f2 = false;
                        try
                        {
                            int gcee = Convert.ToInt32(gce.Split('.')[1]);
                            for (int i = gcee; i > 0; i--)
                            {
                                string str = gce.Split('.')[0] + "." + i.ToString();
                                _open.Reset();
                                _open.ConditionExpress = "索书号='" + str + "'";
                                f1 = _open.Exist("馆藏书目库");
                                _open.Reset();
                                _open.ConditionExpress = "索书号='" + str + "'";
                                f2 = _open.Exist("检索索书号库");
                                if (f1 || f2)
                                {
                                    gce = str;
                                    break;
                                }
                            }
                        }
                        catch { }
                        if (!f1 && !f2)
                            gce = gce.Split('.')[0];
                    }
                    while (true)
                    {
                        string sql = "索书号='" + (F905D + "/" + gce) + "'";
                        if (string.IsNullOrEmpty(gce))
                            sql = "索书号='" + F905D + "'";
                        _open.Reset();
                        _open.ConditionExpress = sql;
                        bool csh = _open.Exist("检索索书号库");
                        if (!csh)
                            break;
                        else
                        {
                            string szjm = _open.GetField("检索索书号库", "主键码").ToString().Trim();
                            if (this.key.Trim().Equals(szjm))
                                break;
                            else
                            {
                                string[] gces = gce.Split('.');
                                if (gces.Length == 1)
                                {
                                    gce += ".1";
                                }
                                else
                                {
                                    gce = gces[0] + "." + (Convert.ToInt32(gces[1]) + 1);
                                }
                            }
                        }
                    }
                }
            }
            if (!string.IsNullOrEmpty(F905D))
            {
                convert.ReplaceSubfield("905", "d", 1, F905D);
                if (!string.IsNullOrEmpty(gce))
                    convert.ReplaceSubfield("905", "e", 1, gce);
                this._MarcText = convert.MarcText;
                SetGridView();
                xrsjk(convert.MarcText);
            }
            else
            {
                ShowMessageBox.ShowMessageBoxTimeout("905D字段内容为空，请检查690字段", "警告", MessageBoxButtons.OK, 3000);
            }
        }

        private void xrsjk(string str)
        {
            if (MessageBox.Show("MARC数据已修改，是否更新？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.OK)
            {
                using (DbOperHandler _open = new Common().Doh())
                {
                    bool flag = false;
                    if (_open.dbType.ToString().Equals("ORACLE") || _open.odbType.ToString().Equals("ORACLE"))
                        flag = true;
                    _open.Reset();
                    _open.ConditionExpress = "主键码=" + key;
                    if (flag)
                    {
                        _open.AddFieldItem("marc1", str);
                        _open.Update("MARC_DATA");
                    }
                    else
                    {
                        _open.AddFieldItem("marc", str);
                        _open.Update("馆藏书目库");
                    }
                }
            }
        }

        private void nmMenu_Click(object sender, EventArgs e)
        {

        }
    }
}